package com.pingao.mp.config.shiro;

import com.pingao.mp.modular.sys.entity.Role;
import com.pingao.mp.modular.sys.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;
@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     * @param principalCollection 对象
     * @return 返回
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) super.getAvailablePrincipal(principalCollection);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<Role> roles = userService.getRolesByUsername(username);
        Set<String> rolesStr = new HashSet<>();
        for (Role role : roles) {
            rolesStr.add(role.getCode());
        }
        authorizationInfo.setRoles(rolesStr);
        Set<String> permissions = userService.getPermissionsByRole(roles);
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken 对象
     * @return 返回
     * @throws AuthenticationException 异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = userService.getUserByUsername(username) == null ? null :userService.getUserByUsername(username).getPassword();
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
